#!/usr/bin/python3
# -*- coding: utf-8 -*-

import time
import hmac, hashlib, base64, urllib
import socket, threading, json

#********************服务端*****************************#
#客户端和服务端第一次建立连接要求发送验证信息:key 主机名#
#可以连接多个客户端，在ClientSocket字典里添加主机名     #
#*******************************************************#
#

#客户端主机名和socket，同时也是Outgoing Key
ClientSocket = {'DingBot': None}
#服务器IP和端口
ServerHost = "0.0.0.0"
Port = 8080

#心跳程序
def heartbeat(host_name, data):
    global ClientSocket
    client_data = data
    while True:
        jsondatac = json.loads(client_data.decode('utf-8'))
        jsondatas = {'time': round(time.time()*1000)}
        print("心跳延时:",jsondatas['time'] - jsondatac['time'])
        ClientSocket[host_name].send(bytes(json.dumps(jsondatas),'utf-8'))
        client_data = ClientSocket[host_name].recv(1024)
        print(client_data)
        if client_data == b'':
            ClientSocket[host_name].close()
            ClientSocket[host_name] = None
            break

#客户端验证与消息转发
def handle_client(cs,ca):

    global ClientSocket

    client_data = cs.recv(1024)

    print("[%s]Data:%s"%(ca,client_data.decode('utf-8')))

    try:
        client_dataline = client_data.decode('utf-8').splitlines()
    except Exception as err:
        return
    #客户端首次连接验证
    if client_dataline[0] == 'Dingding':
        status_data = b'connect is ok'
        ClientSocket[client_dataline[1]] = cs
        ClientSocket[client_dataline[1]].send(status_data)
        print(ClientSocket['DingBot'])
    #
        client_data = cs.recv(1024)
        client_dataline[1] = threading.Thread(target = heartbeat, args = (client_dataline[1],client_data))
        client_dataline[1].start()
    #接收Outgoing机器人消息，且发送到客户端
    elif client_dataline[0] == 'POST /dingbot HTTP/1.1':
        token = client_dataline[1].split(': ')
        print(ClientSocket[token[1]])
        ClientSocket[token[1]].send(bytes(client_dataline[9],'utf-8')) 
    #其他连接返回信息
    else:
        response_start_line = "HTTP/1.1 200 OK\r\n"
        response_headers = "Server: My server\r\n"
        response_body = "<h1>HTTP server is working!</h1>"
        response = response_start_line + response_headers + "\r\n" + response_body
        cs.send(bytes(response, 'utf-8'))
        cs.close()


if __name__ == '__main__':
    print('--------HTTP Server Start--------')
    ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    ss.bind((ServerHost,Port))
    ss.listen(5)


    while True:
        cs, caddr = ss.accept()
        print("[%s, %s]用户已连接"%caddr)

        HandleClient_Thread = threading.Thread(target=handle_client, args=(cs,caddr))
        HandleClient_Thread.start()
